package cn.com.qingz.modules.user.controller;

import cn.com.qingz.core.model.DefaultResp;
import cn.com.qingz.core.utils.StringUtil;
import cn.com.qingz.modules.user.model.*;
import cn.com.qingz.modules.user.service.*;
import cn.com.qingz.modules.user.vo.DesignSearchCondition;
import cn.com.qingz.modules.user.vo.HouseModelSearchCondition;
import cn.com.qingz.modules.user.vo.SampleHouseSearchCondition;
import com.alibaba.fastjson.JSON;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("app/*")
public class AppController {

    @Autowired
    private UserDesignService userDesignService;

    @Autowired
    private ModelService modelService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Resource
    private CustomerService customerService;

    @Autowired
    private HouseModelService houseModelService;

    @Autowired
    private BillGoodsService billGoodsService;

    @Autowired
    private VersionService versionService;

    @Autowired
    private SampleHouseService sampleHouseService;

    /**
     * 获取分类
     *
     * @return
     */
    @RequestMapping("Resourceapi/GetCategoryList")
    @ResponseBody
    public DefaultResp<List<Category>> getCategoryList() {
        DefaultResp<List<Category>> resp = new DefaultResp<>();
        List<Category> list = categoryService.queryAll();
        resp.setData(list);
        return resp;
    }

    /**
     * 获取品牌
     *
     * @return
     */
    @RequestMapping("Resourceapi/GetBrandList")
    @ResponseBody
    public DefaultResp<List<Brand>> getBrandList() {
        DefaultResp<List<Brand>> resp = new DefaultResp<>();
        List<Brand> list = brandService.queryAll();
        resp.setData(list);
        return resp;
    }

    /**
     * 用户登录
     *
     * @return
     */
    @RequestMapping("UserApi/Login")
    @ResponseBody
    public DefaultResp<Map<String, Object>> login(String userName, String password, HttpServletRequest request) {
        DefaultResp<Map<String, Object>> res = new DefaultResp<>();
        Customer customer = customerService.doLogin(userName, password, request);
        Map<String, Object> data = new HashMap<>();
        data.put("token", customer.getToken());
        data.put("userName", customer.getRealname());
        data.put("userid", customer.getCustomerid().toString());
        data.put("type", customer.getUsertype());
        res.setData(data);
        return res;
    }

    /**
     * 上传设计图
     *
     * @return
     */
    @RequestMapping("UserDesignApi/AddOrUpdateUserDesign")
    @ResponseBody
    public DefaultResp<String> AddOrUpdateUserDesign(String token, Design design) {
        customerService.verifyToken(token);
        DefaultResp<String> resp = new DefaultResp<>();
        userDesignService.doAddOrUpdate(design);
        resp.setData(design.getDesignid().toString());
        return resp;
    }

    /**
     * 获取设计图
     *
     * @param token
     * @param designId
     * @return
     */
    @RequestMapping("UserDesignApi/GetUserDesignByDesignID")
    @ResponseBody
    public DefaultResp<Design> GetUserDesignByDesignID(String token, Integer designId) {
        customerService.verifyToken(token);
        DefaultResp<Design> resp = new DefaultResp<>();
        Design design = userDesignService.get(designId);
        resp.setData(design);
        return resp;
    }

    /**
     * 查询设计图
     *
     * @param token
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping("UserDesignApi/getUserDesign")
    @ResponseBody
    public Map<String, Object> queryByPage(String token, DesignSearchCondition condition, @RequestParam(required = false, defaultValue = "0") int start,
                                           @RequestParam(required = false, defaultValue = "10") int limit) {
        System.out.println("token" + token);
        customerService.verifyToken(token);
        PageList<?> list = userDesignService.queryForPage(condition, start, limit);
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("total", list.getPaginator().getTotalCount());
        int total = list.getPaginator().getTotalCount();
        int totalpage = 0;
        if (total % limit == 0) {
            totalpage = total / limit;
        } else {
            totalpage = (total / limit) + 1;
        }
        res.put("totalpage", totalpage);
        res.put("data", list);
        return res;
    }

    /**
     * 根据分类id获取模型
     *
     * @param token
     * @return
     */
    @RequestMapping("Resourceapi/GetResourceByCategoryId")
    @ResponseBody
    public DefaultResp<List<Model>> getResourceByCategoryId(String token, @RequestParam(required = true) String categoryId) {
        System.out.println("token" + token);
        customerService.verifyToken(token);
        DefaultResp<List<Model>> resp = new DefaultResp<>();
        List<Model> list = modelService.getModelsByCategoryId(categoryId);
        resp.setData(list);
        return resp;
    }

    /**
     * 删除用户设计
     *
     * @param token
     * @param designid
     * @return
     */
    @RequestMapping("UserDesignApi/DeleteUserDesign")
    @ResponseBody
    public DefaultResp<String> DeleteUserDesign(String token, @RequestParam(required = true) Integer designid) {
        System.out.println("token" + token);
        customerService.verifyToken(token);
        DefaultResp<String> resp = new DefaultResp<>();
        Design design = new Design();
        design.setDesignid(designid);
        userDesignService.doDel(design);
        return resp;
    }

    /**
     * 返回指定的户型
     *
     * @param token
     * @param housemodelid
     * @return
     */
    @RequestMapping("HouseModelApi/GetHouseModelByID")
    @ResponseBody
    public DefaultResp<HouseModel> GetHouseModelByID(String token, @RequestParam(required = true) Integer housemodelid) {
        System.out.println("token" + token);
        customerService.verifyToken(token);
        DefaultResp<HouseModel> resp = new DefaultResp<>();
        HouseModel houseModel = houseModelService.get(housemodelid);
        resp.setData(houseModel);
        return resp;
    }

    /**
     * 户型搜索
     *
     * @param condition
     * @param pageindex
     * @param pagesize
     * @return
     */
    @RequestMapping("HouseModelApi/SearchHouseMode")
    @ResponseBody
    public Map<String, Object> searchHouseMode(HouseModelSearchCondition condition, @RequestParam(required = false, defaultValue = "0") int pageindex,
                                               @RequestParam(required = false, defaultValue = "10") int pagesize) {
        PageList<?> list = houseModelService.queryForPage(condition, pageindex, pagesize);
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("totalCount", list.getPaginator().getTotalCount());
        int total = list.getPaginator().getTotalCount();
        int totalpage = 0;
        if (total % pagesize == 0) {
            totalpage = total / pagesize;
        } else {
            totalpage = (total / pagesize) + 1;
        }
        res.put("totalpage", totalpage);
        res.put("data", list);
        return res;
    }

    /**
     * 搜索样板间
     *
     * @param condition
     * @param pageindex
     * @param pagesize
     * @return
     */
    @RequestMapping("Sample/SearchHouseMode")
    @ResponseBody
    public Map<String, Object> searchSampleHouseMode(SampleHouseSearchCondition condition, @RequestParam(required = false, defaultValue = "0") int pageindex,
                                                     @RequestParam(required = false, defaultValue = "10") int pagesize) {
        PageList<SampleHouse> list = sampleHouseService.queryForPage(condition, pageindex, pagesize);
        Map<String, Object> res = new HashMap<>();
        res.put("totalCount", list.getPaginator().getTotalCount());
        int total = list.getPaginator().getTotalCount();
        int totalpage = 0;
        if (total % pagesize == 0) {
            totalpage = total / pagesize;
        } else {
            totalpage = (total / pagesize) + 1;
        }
        res.put("totalpage", totalpage);
        res.put("data", list);
        return res;
    }

    /**
     * 根据模型id获取模型
     *
     * @param token
     * @param idlist
     * @return
     */
    @RequestMapping("Resourceapi/GetResourceByDetailsIDList")
    @ResponseBody
    public DefaultResp<List<Model>> getByIdList(String token, String idlist) {
        System.out.println("token" + token);
        customerService.verifyToken(token);
        DefaultResp<List<Model>> resp = new DefaultResp<>();
        List<Model> list = modelService.getModelByListId(idlist);
        resp.setData(list);
        return resp;
    }

    /**
     * 新增/更新户型
     *
     * @param token
     * @param houseModel
     * @return
     */
    @RequestMapping("HouseModelApi/UpdateHouseModel")
    @ResponseBody
    public DefaultResp<String> UpdateHouseModel(String token, HouseModel houseModel) {
        System.out.println("token" + token);
        customerService.verifyToken(token);
        DefaultResp<String> resp = new DefaultResp<>();
        Integer t = houseModelService.doSaveOrUpdate(houseModel);
        resp.setData(t.toString());
        return resp;
    }

    @RequestMapping("HouseModelApi/SaveGoodsList")
    @ResponseBody
    public DefaultResp<String> SaveGoodsList(String token, String json) {
        List<BillGoods> list = JSON.parseArray(json, BillGoods.class);
        System.out.println("token" + token);
        customerService.verifyToken(token);
        DefaultResp<String> resp = new DefaultResp<>();
        billGoodsService.doSave(list);
        return resp;
    }

    @RequestMapping("Application/Version")
    @ResponseBody
    public DefaultResp<Boolean> getVersion(@RequestParam(required = true) String version) {
        DefaultResp<Boolean> resp = new DefaultResp<Boolean>();
        Version v = versionService.get("com.codeblue.app");
        boolean isNew = v.getVersion().equals(version);
        resp.setData(isNew);
        return resp;
    }


    //设置设计的图片
    @RequestMapping("setDesginPic")
    @ResponseBody
    public DefaultResp<String> setDesginPic(Design design) {
        DefaultResp<String> resp = new DefaultResp<String>();
        userDesignService.doUpdate(design);
        String url = "http://www.lipe-home.com/app/showMyVRDesgin.do?id=" + design.getDesignid();
        resp.setData(url);
        return resp;
    }


    @RequestMapping("batchSaveModels")
    @ResponseBody
    public DefaultResp<String> batchSaveModels(@RequestBody List<Model> models) {
        DefaultResp<String> resp = new DefaultResp<>();
        StringBuffer sb = new StringBuffer();
        for (Model model : models) {
            try {
                Category c = categoryService.findByName(model.getCategory());
                if (c != null) {
                    model.setCategoryId(c.getCategoryid());
                }

                Brand b = brandService.findByName(model.getBrand());
                if (b != null) {
                    model.setBrandId(b.getBrandId());
                }
                modelService.doAddOrUpdate(model);
            } catch (Exception e) {
                e.printStackTrace();
                sb.append("模型Id" + model.getModelId() + "保存失败" + e.getMessage()).append(",");
            }
        }
        if (!StringUtil.isEmpty(sb.toString())) {
            resp.setCode("0001");
        }
        resp.setData(sb.toString());
        return resp;
    }


    /**
     * 显示我的全景图
     */
    @RequestMapping("showMyVRDesgin")
    public String showMyVRDesgin(Integer id, HttpServletRequest request) {
        request.setAttribute("id", id);
        return "vr";
    }


    @RequestMapping
    public void getVrXMLConfig(HttpServletResponse response, Integer id) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/xml");
        Design design = userDesignService.get(id);
        String pics = design.getBigmaps();
        if (StringUtils.isEmpty(pics)) {
            return;
        }
        String picList[] = pics.split(",");

        ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader();
        Configuration cfg = Configuration.defaultConfiguration();
        GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
        Template t = gt.getTemplate("/vr.tpl");

        t.binding("imageURLList", Arrays.asList(picList));
        String str = t.render();
        response.getWriter().print(str);
    }
}
